class Solution {
    bool vis[6][6];
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    int path;
    int m, n;
public:
    bool exist(vector<vector<char>>& board, string word) {
        m = board.size(), n = board[0].size(), path = 0;;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
            {
                if (board[i][j] == word[0])
                {
                    vis[i][j] = true;
                    path++;
                    if (dfs(board, i, j, word))
                        return true;
                    vis[i][j] = false;
                    path--;
                }
            }
        return false;
    }

    bool dfs(vector<vector<char>>& board, int i, int j, const string& word)
    {
        if (path == word.size())
            return true;

        for (int k = 0; k < 4; k++)
        {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n &&
                !vis[x][y] && word[path] == board[x][y])
            {
                vis[x][y] = true;
                path++;
                if (dfs(board, x, y, word))
                    return true;
                vis[x][y] = false;
                path--;
            }
        }
        return false;
    }
};